package com.typing.battle.activity;


import java.util.HashMap;

import org.json.JSONObject;

import com.typing.battle.R;

import com.typing.battle.listener.OnDataSyncCompleteListener;
import com.typing.battle.util.PreferenceMgr;
import com.typing.battle.util.ServerComunicationUtil;
import com.typing.battle.value.ServerComunicationDTO;
import com.typing.battle.view.ChatRoomListView;


import android.app.Activity;
import android.content.Intent;

import android.os.Bundle;

import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;
import android.widget.AbsListView.OnScrollListener;
import android.widget.LinearLayout.LayoutParams;


public class TypingBattleChatRoomListActivity  extends TypingBattleRootActivity {
    
	private String _ID;
	public static ChatRoomListView chatListView;
	
	private LinearLayout chatWindow,progressLayout;
	private Button searchBtn;
	private EditText searchText;
	private RelativeLayout relLayout;
	private PreferenceMgr mgr;
	private HashMap<String,Intent> intentMap = new HashMap<String,Intent>();
	public static final int CHAT_ROOM_CREATE = 0;
    @Override
    public void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.battle_chat_room_list);
        mgr = PreferenceMgr.getInstance(this);
		getIntent().getStringExtra("");   
		
		
    	relLayout = (RelativeLayout) findViewById(R.id.layout_chat_room_list_rel);
    	chatWindow = (LinearLayout)relLayout.findViewById(R.id.layout_chat_room_list);
    	
		chatListView = new ChatRoomListView(this);
		chatWindow.addView(chatListView,new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT)); 
		progressLayout = (LinearLayout) View.inflate(this, R.layout.battle_list_progress, null);
    	progressLayout.setVisibility(View.INVISIBLE);
    	chatListView.addFooterView(progressLayout);
    	chatListView.setOnScrollListener(new OnScrollListener() {
	
			// @Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub
				
			}
			
			// @Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub
				
				if ((firstVisibleItem + visibleItemCount) == totalItemCount) {
					Log.v("list", "IN, totalItemCount = " + totalItemCount);
					
					if (chatListView.getTotalCount() > chatListView.getCurrentIndex()) {
						progressLayout.setVisibility(View.VISIBLE);
						chatListView.getNextList();
					} else {
						progressLayout.setVisibility(View.INVISIBLE);
					}
					
				}
			}
		});    
    	searchText = (EditText)findViewById(R.id.input_search_chat_room);
    	searchBtn = (Button)findViewById(R.id.btn_search);
    	searchBtn.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				chatListView.searchChatRoom(searchText.getText().toString());
			}
    		
    	});
    } 
    
    @Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		menu.add("방만들기");
		menu.add("랜덤채팅");
		menu.add("새로고침");
		return super.onCreateOptionsMenu(menu);
	}
    @Override
	public boolean onOptionsItemSelected(MenuItem item) {
    	if(item.getTitle().equals("방만들기")){
			Intent intent = new Intent(this,TypingBattleChatRoomCreateActivity.class);
			startActivityForResult(intent, CHAT_ROOM_CREATE);
    	}else if(item.getTitle().equals("랜덤채팅")){
    		Intent intent = new Intent(this,TypingBattleChatRoomActivity.class);
    		ServerComunicationDTO dto = new ServerComunicationDTO();
    		
			dto.setActionType(ServerComunicationUtil.TYPE_CHAT_ROOM_RANDOM);
			dto.setResponseType(ServerComunicationUtil.RETURN_TYPE_STRING);
			dto.setUserEmail(mgr.getData(PreferenceMgr.USER_EMAIL_KEY, ""));
			try{
				ServerComunicationUtil.serverAction(dto,this,this);
			}catch(Exception e){
				
			}
    	}else {
    		chatListView.refreshData();
    	}
		return super.onOptionsItemSelected(item);
	}
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    	// TODO Auto-generated method stub
    	switch (requestCode) { 
        case CHAT_ROOM_CREATE:  
        	//Added by KM.
        	if(data == null)	return;
            // If the operation succeeded
        	if(data.getBooleanExtra("RESULT", false)){
        		Intent intent = new Intent(this,TypingBattleChatRoomActivity.class);
        		ServerComunicationDTO dto = new ServerComunicationDTO();
    			dto.setActionType(ServerComunicationUtil.TYPE_CHAT_ROOM_MASTER_JOIN);
    			dto.setResponseType(ServerComunicationUtil.RETURN_TYPE_STRING);
    			dto.setUserEmail(mgr.getData(PreferenceMgr.USER_EMAIL_KEY, ""));
    			dto.setChatRoomId(data.getStringExtra("CHAT_ROOM_ID"));
    			intent.putExtra("CHAT_ROOM_ID", data.getStringExtra("CHAT_ROOM_ID"));
    			intent.putExtra("isChampion", true);
    			try{
    				ServerComunicationUtil.serverAction(dto,this,this);
    			}catch(Exception e){
    				
    			}
    			intentMap.put("CREATE", intent);
    			//startActivity(intent);
        	}
    	}
    	super.onActivityResult(requestCode, resultCode, data);
    }
    
    @Override
    protected void onResume() {
    	// TODO Auto-generated method stub
    	chatListView.refreshData();
    	super.onResume();
    }
    
    @Override
	public void onSyncComplete(int resultCode, ServerComunicationDTO dto, Object resultObj) {
		if(resultCode == OnDataSyncCompleteListener.RESULT_SYNC_FAIL){
			if(resultObj!=null)
				ServerComunicationUtil.showNotify((String)resultObj, this);
		}else{
			if(dto.getActionType() == ServerComunicationUtil.TYPE_CHAT_ROOM_RANDOM){
				String result = null;
				try{
					result = (String)resultObj;
					if("FAIL".equals(result)){
						Toast toast = Toast.makeText(this, "랜덤채팅에 실패하였습니다." ,Toast.LENGTH_SHORT);
						toast.show();
					}else{
						Log.d("chatRoomId",result);
						Intent intent = new Intent(this,TypingBattleChatRoomActivity.class);
		        		ServerComunicationDTO dto1 = new ServerComunicationDTO();
		    			dto1.setActionType(ServerComunicationUtil.TYPE_CHAT_ROOM_JOIN);
		    			dto1.setResponseType(ServerComunicationUtil.RETURN_TYPE_STRING);
		    			dto1.setUserEmail(mgr.getData(PreferenceMgr.USER_EMAIL_KEY, ""));
		    			dto1.setChatRoomId(result);
		    			intent.putExtra("CHAT_ROOM_ID", result);
		    			intent.putExtra("isChampion", true);
		    			try{
		    				ServerComunicationUtil.serverAction(dto1,this,this);
		    			}catch(Exception e){
		    				
		    			}
		    			intentMap.put("RANDOM", intent);
		    			//startActivity();
						//finish();
						
					}
				}catch(Exception e){
					
				}
			}else if(dto.getActionType() == ServerComunicationUtil.TYPE_CHAT_ROOM_JOIN){
				String result = (String)resultObj;
				Log.d("xxxxxxx",result);
				if("OK".equals(result)){
					Log.d("xxxxxxxxx",result);
					startActivity(intentMap.get("RANDOM"));
				}
			}else if(dto.getActionType() == ServerComunicationUtil.TYPE_CHAT_ROOM_MASTER_JOIN){
				String result = (String)resultObj;
				Log.d("zzzzzzzzzz",result);
				if("OK".equals(result)){
					Log.d("zzzzzzzzzz",result);
					startActivity(intentMap.get("CREATE"));
				}else {
					
				}
			}
		}
		super.onSyncComplete(resultCode, dto, resultObj);
	}
    
}